package com.hdjk.view.activity.personalcenter;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.liangmutian.mypicker.DateUtil;
import com.hdjk.view.R;
import com.hdjk.view.adapter.BuyPlanExecuteHistoryAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.dialog.EditTextPwdDialog;
import com.hdjk.view.entity.BuyPlanEntity;
import com.hdjk.view.entity.BuyPlanExecuteHistoryEntity;
import com.hdjk.view.network.PlanNetWork;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sxy on 2017/11/15.
 */

public class BuyPlanDetailsActivity extends BaseActivity implements View.OnClickListener {
    private BuyPlanEntity mEntity;

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private TextView tv_amounts;
    private TextView tv_sum;
    private TextView tv_time;
    private TextView tv_is_extended;
    private TextView tv_previous_time;
    private TextView tv_next_time;
    private TextView tv_bank_card;
    private TextView tv_fund_name;
    private com.lst.projectlib.component.ListView.ListViewForScrollView lv_data_list;
    private RelativeLayout rel_stop;
    private TextView tv_empty;
    private TextView tv_stop;
    private RelativeLayout rel_modify;
    private TextView tv_modify;
    private RelativeLayout rel_pause;
    private TextView tv_pause;
    // End Of Content View Elements

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        tv_amounts = (TextView) findViewById(R.id.tv_amounts);
        tv_sum = (TextView) findViewById(R.id.tv_sum);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_is_extended = (TextView) findViewById(R.id.tv_is_extended);
        tv_previous_time = (TextView) findViewById(R.id.tv_previous_time);
        tv_next_time = (TextView) findViewById(R.id.tv_next_time);
        tv_bank_card = (TextView) findViewById(R.id.tv_bank_card);
        tv_fund_name = (TextView) findViewById(R.id.tv_fund_name);
        lv_data_list = (com.lst.projectlib.component.ListView.ListViewForScrollView) findViewById(R.id.lv_data_list);
        rel_stop = (RelativeLayout) findViewById(R.id.rel_stop);
        tv_empty = (TextView) findViewById(R.id.tv_empty);
        tv_stop = (TextView) findViewById(R.id.tv_stop);
        rel_modify = (RelativeLayout) findViewById(R.id.rel_modify);
        tv_modify = (TextView) findViewById(R.id.tv_modify);
        rel_pause = (RelativeLayout) findViewById(R.id.rel_pause);
        tv_pause = (TextView) findViewById(R.id.tv_pause);
    }



    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_buy_plan_details);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        ttb_title_bar.setFocusable(true);
        ttb_title_bar.setFocusableInTouchMode(true);
        ttb_title_bar.requestFocus();
    }

    @Override
    protected void initData() {
        mEntity = (BuyPlanEntity) getIntent().getExtras().getSerializable("entity");
        setViews();
        getBuyPlanExecuteHistory();
    }

    private void setViews(){
        if (mEntity != null) {
            ttb_title_bar.setNavTitle(mEntity.getName());
            tv_amounts.setText(mEntity.getSum());
            tv_bank_card.setText(mEntity.getInvestorPayBankName()+" "+mEntity.getInvestorPayBankAccountNumber());
            tv_is_extended.setText(mEntity.getPostponeDeduction().equals("1") ? "是" : "否");
            tv_next_time.setText(DateUtil.formatDate(mEntity.getNextRunDate(), "yyyy-MM-dd"));
            tv_previous_time.setText(DateUtil.formatDate(mEntity.getUpdatedDate(), "yyyy-MM-dd"));
            tv_time.setText(mEntity.getCycleName() + " " + mEntity.getCycleDayName());
            tv_fund_name.setText(mEntity.getProducts().get(0).getFundName());
            if ("active".equals(mEntity.getRspStatus())) {
                rel_modify.setOnClickListener(this);
                rel_pause.setOnClickListener(this);
                rel_stop.setOnClickListener(this);
            } else if ("suspend".equals(mEntity.getRspStatus())) {
                tv_pause.setText("重启");
                rel_modify.setOnClickListener(this);
                rel_pause.setOnClickListener(this);
                rel_stop.setOnClickListener(this);
            } else if ("terminated".equals(mEntity.getRspStatus())) {
                rel_pause.setVisibility(View.GONE);
                rel_modify.setVisibility(View.GONE);
                tv_stop.setText("已终止");
            }
        }
    }

    private void getBuyPlan(){
        mDialog.show();
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(BuyPlanDetailsActivity.this));
            obj.put("rspId", mEntity.getRspId());
            PlanNetWork.getBuyPlanList(UserTokenUtil.getToken(BuyPlanDetailsActivity.this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess() && msg.getData() != null) {
                        List<BuyPlanEntity> tempList = (ArrayList) msg.getData();
                        mEntity=tempList.get(0);
                        setViews();
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getBuyPlanExecuteHistory(){
        mDialog.show();
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(BuyPlanDetailsActivity.this));
            obj.put("rspId", mEntity.getRspId());
            PlanNetWork.getBuyPlanExecuteHistory(UserTokenUtil.getToken(BuyPlanDetailsActivity.this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess() && msg.getData() != null) {
                        BuyPlanExecuteHistoryEntity entity= (BuyPlanExecuteHistoryEntity) msg.getData();
                        if (entity!=null) {
                            tv_sum.setText(entity.getAllTransactionAmount());
                            if (entity.getProducts()!=null&&entity.getProducts().size()>0){
                                lv_data_list.setVisibility(View.VISIBLE);
                                tv_empty.setText("没有更多数据");
                                BuyPlanExecuteHistoryAdapter adapter=new BuyPlanExecuteHistoryAdapter(BuyPlanDetailsActivity.this);
                                adapter.setDataList(entity.getProducts());
                                lv_data_list.setAdapter(adapter);
                            }else {
                                lv_data_list.setVisibility(View.GONE);
                                tv_empty.setText("暂无数据");
                            }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        EditTextPwdDialog dialog;
        switch (view.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.rel_stop:
                dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
                    @Override
                    public void onSureClick(String txt) {
                        mDialog.show();
                        JSONObject object = new JSONObject();
                        try {
                            object.put("accountNumber", UserTokenUtil.getUserName(BuyPlanDetailsActivity.this));
                            object.put("rspId", mEntity.getRspId());
                            object.put("password", txt);
                            PlanNetWork.stopPlan(UserTokenUtil.getToken(BuyPlanDetailsActivity.this), object.toString(), new CallBackListener() {
                                @Override
                                public void onCallBackCompleted(Msg msg) {
                                    mDialog.cancel();
                                    if (msg != null && msg.getSuccess()) {
                                        ToastUtils.showShortToast(BuyPlanDetailsActivity.this, "操作成功");
                                        rel_pause.setVisibility(View.GONE);
                                        rel_modify.setVisibility(View.GONE);
                                        tv_stop.setText("已终止");
                                        tv_stop.setEnabled(false);
                                        Intent intent = new Intent(Constant.INTENT_FILTER_STRING_AFTER_BUY_PLAN_MODIFY_STATE);
                                        sendBroadcast(intent);
                                    } else {
                                        if (msg != null && !TextUtils.isEmpty(msg.getMsg()) && !"null".equals(msg.getMsg())) {
                                            ToastUtils.showShortToast(BuyPlanDetailsActivity.this, msg.getMsg());
                                        } else {
                                            ToastUtils.showShortToast(BuyPlanDetailsActivity.this, "操作失败");
                                        }
                                    }
                                }

                                @Override
                                public void onCallBackError(Msg msg) {
                                    mDialog.cancel();
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                dialog.show();
                break;
            case R.id.rel_modify:
                Intent intent = new Intent(BuyPlanDetailsActivity.this, PlanFundModifyActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("entity", mEntity);
                intent.putExtras(bundle);
                startActivityForResult(intent,333);
                break;
            case R.id.rel_pause:
                dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
                    @Override
                    public void onSureClick(String txt) {
                        mDialog.show();
                        JSONObject object = new JSONObject();
                        try {
                            object.put("accountNumber", UserTokenUtil.getUserName(BuyPlanDetailsActivity.this));
                            object.put("rspId", mEntity.getRspId());
                            object.put("password", txt);
                            if ("active".equals(mEntity.getRspStatus())){
                                PlanNetWork.pausePlan(UserTokenUtil.getToken(BuyPlanDetailsActivity.this), object.toString(), new CallBackListener() {
                                    @Override
                                    public void onCallBackCompleted(Msg msg) {
                                        mDialog.cancel();
                                        if (msg != null && msg.getSuccess()) {
                                            ToastUtils.showShortToast(BuyPlanDetailsActivity.this, "操作成功");
                                            tv_pause.setText("重启");
                                            Intent intent = new Intent(Constant.INTENT_FILTER_STRING_AFTER_BUY_PLAN_MODIFY_STATE);
                                            sendBroadcast(intent);
                                        } else {
                                            if (msg != null && !TextUtils.isEmpty(msg.getMsg()) && !"null".equals(msg.getMsg())) {
                                                ToastUtils.showShortToast(BuyPlanDetailsActivity.this, msg.getMsg());
                                            } else {
                                                ToastUtils.showShortToast(BuyPlanDetailsActivity.this, "操作失败");
                                            }
                                        }
                                    }

                                    @Override
                                    public void onCallBackError(Msg msg) {
                                        mDialog.cancel();
                                    }
                                });
                            }
                            if ("suspend".equals(mEntity.getRspStatus())){
                                PlanNetWork.restartPlan(UserTokenUtil.getToken(BuyPlanDetailsActivity.this), object.toString(), new CallBackListener() {
                                    @Override
                                    public void onCallBackCompleted(Msg msg) {
                                        mDialog.cancel();
                                        if (msg != null && msg.getSuccess()) {
                                            ToastUtils.showShortToast(BuyPlanDetailsActivity.this, "操作成功");
                                            tv_pause.setText("暂停");
                                            Intent intent = new Intent(Constant.INTENT_FILTER_STRING_AFTER_BUY_PLAN_MODIFY_STATE);
                                            sendBroadcast(intent);
                                        } else {
                                            if (msg != null && !TextUtils.isEmpty(msg.getMsg()) && !"null".equals(msg.getMsg())) {
                                                ToastUtils.showShortToast(BuyPlanDetailsActivity.this, msg.getMsg());
                                            } else {
                                                ToastUtils.showShortToast(BuyPlanDetailsActivity.this, "操作失败");
                                            }
                                        }
                                    }

                                    @Override
                                    public void onCallBackError(Msg msg) {
                                        mDialog.cancel();
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==333&&resultCode==333){
            getBuyPlan();
        }
    }
}
